package com.zxl.yjb.activity.home.position;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zxl.yjb.R;
import com.zxl.yjb.activity.my.PositionAddActivity;
import com.zxl.yjb.adapter.PositionAdapter;
import com.zxl.yjb.app.Const;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.AddressBookBean;
import com.zxl.yjb.bean.LocationBean;
import com.zxl.yjb.bean.MessageEvent;
import com.zxl.yjb.bean.PoiItemExt;
import com.zxl.yjb.bean.PoiItemSB;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.DisplayUtil;
import com.zxl.yjb.utils.LogUtil;
import com.zxl.yjb.utils.SaveBeanUtil;
import com.zxl.yjb.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PositionSelectActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_page_title)
    TextView tv_page_title;
    @BindView(R.id.iv_down)
    ImageView iv_down;
    @BindView(R.id.edtTxt_amcham_name)
    EditText edtTxt_amcham_name;
    @BindView(R.id.iv_delete)
    ImageView iv_delete;
    @BindView(R.id.ll_search)
    LinearLayout ll_search;
    @BindView(R.id.ll_position_nearby)
    LinearLayout ll_position_nearby;
    @BindView(R.id.ll_position_history)
    LinearLayout ll_position_history;
    @BindView(R.id.ll_myposition)
    LinearLayout ll_myposition;
    @BindView(R.id.rv_position_list)
    RecyclerView rv_position_list;
    @BindView(R.id.view_near)
    View view_near;
    @BindView(R.id.view_history)
    View view_history;
    @BindView(R.id.view_myposition)
    View view_myposition;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;

    private DataManager dataManager;

    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索

    private RecyclerView.LayoutManager layoutManager;
    private ArrayList<PoiItem> poiItemList = new ArrayList<>();
    private ArrayList<PoiItemExt> historyPoiItemList = new ArrayList<>();
    private ArrayList<PoiItemSB> poiItemSBS = new ArrayList<>();
    private PositionAdapter positionAdapter;
    private LatLonPoint lp;
    private LocationBean locationBean;

    private double lon;
    private double lat;

    private final String LIST_TYPE_SEARCH = "search";
    private final String LIST_TYPE_NEAR = "near";

    private boolean isHistory = false;//历史地址选项

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_position_select);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        historyPoiItemList = (ArrayList<PoiItemExt>) SaveBeanUtil.getBean(PositionSelectActivity.this, Const.POSITION_HISTORY);
        locationBean = (LocationBean) SaveBeanUtil.getBean(this, Const.LOCATION_LNGLAT);
        if (locationBean != null) {
            lon = locationBean.getLng();
            lat = locationBean.getLat();
        } else {
            locationBean = new LocationBean();
        }
        lp = new LatLonPoint(lat, lon);
        initView();
        poiItemList.clear();
        getSearchPosition(LIST_TYPE_NEAR);
    }

    @Override
    protected void initView() {
        tv_page_title.setText("选择接单位置");
        tvConfirm.setText("添加");
        layoutManager = new LinearLayoutManager(this);
        rv_position_list.setLayoutManager(layoutManager);
        positionAdapter = new PositionAdapter(R.layout.item_position_search, poiItemList);
        rv_position_list.setAdapter(positionAdapter);
        positionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (poiItemList != null) {
                    LatLonPoint latLonPoint = poiItemList.get(position).getLatLonPoint();
                    if (latLonPoint != null) {
                        EventBus.getDefault().post(new MessageEvent("position", new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude())));
                        saveHisPotision(poiItemList.get(position));
                    }

                }
                finish();
            }
        });

        positionAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, final int position) {
                if (!isHistory)
                    return true;
                DisplayUtil.diaplayDialog(PositionSelectActivity.this, "提示", "确定要删除此条记录吗？", "取消", "确定", null, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        removeHisPosition(position);
                    }
                });

                return true;
            }
        });
        edtTxt_amcham_name.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    view_near.setVisibility(View.INVISIBLE);
                    view_history.setVisibility(View.INVISIBLE);
                    getSearchPosition(LIST_TYPE_SEARCH);
                }
                return false;
            }
        });
    }


    private void getSearchPosition(String type) {
        isHistory = false;
        String keyWord = "";
        keyWord = edtTxt_amcham_name.getText().toString();

        if (type.equals(LIST_TYPE_NEAR)) {
            keyWord = "";
        } else {
            if (TextUtils.isEmpty(keyWord)) {
                ToastUtils.show(this, "请输入搜索关键字");
                return;
            }
        }

        query = new PoiSearch.Query(keyWord, "", locationBean.getCitycode());
        query.setPageSize(20);
        query.setPageNum(0);
        query.setCityLimit(true);

        poiSearch = new PoiSearch(this, query);

        if (type.equals(LIST_TYPE_NEAR)) {
            poiSearch.setBound(new PoiSearch.SearchBound(lp, 5000, true));
        }

        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                LogUtil.e("aa", "aa");
                poiItemList.clear();
                poiItemList.addAll(poiResult.getPois());
                positionAdapter.notifyDataSetChanged();
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {
                LogUtil.e("aa", "aa");
            }
        });
        poiSearch.searchPOIAsyn();
    }


    private void getMyPosition() {
        isHistory = false;
        dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("page", 0 + "");
        map.put("count", 100 + "");
        ObserverOnNextListener<AddressBookBean> listener = new ObserverOnNextListener<AddressBookBean>() {
            @Override
            public void onNext(AddressBookBean addressBookBean) {
//                poiItemSBS.addAll(poiItemSBList);
                for (AddressBookBean.DataBean poiItemSB : addressBookBean.getData()) {
                    PoiItem poiItem = new PoiItem(poiItemSB.getId()+"", new LatLonPoint(poiItemSB.getLatitude(), poiItemSB.getLongitude()), poiItemSB.getName(), poiItemSB.getCity()+poiItemSB.getDistrict()+poiItemSB.getStreet()+poiItemSB.getOthers());
                    poiItemList.add(poiItem);
                }
                positionAdapter.notifyDataSetChanged();
            }
        };
        dataManager.addressBook_list(new ProgressObserver<AddressBookBean>(listener, this), map);

    }


    private void getHistoryPosition() {
        isHistory = true;
        if (historyPoiItemList == null || historyPoiItemList.size() == 0) {
            ToastUtils.show(PositionSelectActivity.this, "暂无历史地址信息");
            poiItemList.clear();
            positionAdapter.notifyDataSetChanged();
            return;
        }
        poiItemList.clear();
        for (int i = 0; i < historyPoiItemList.size(); i++) {
            PoiItem poiItem = new PoiItem(historyPoiItemList.get(i).getId(), new LatLonPoint(historyPoiItemList.get(i).getLat(), historyPoiItemList.get(i).getLon()), historyPoiItemList.get(i).getTitle(), historyPoiItemList.get(i).getSnippets());
            poiItemList.add(poiItem);
        }

        positionAdapter.notifyDataSetChanged();
    }

    private void saveHisPotision(PoiItem poiItem) {
        if (historyPoiItemList == null)
            historyPoiItemList = new ArrayList<>();
        if (historyPoiItemList.size() >= 20) {
            historyPoiItemList.remove(historyPoiItemList.size() - 1);
        }
        PoiItemExt poiItemExt = new PoiItemExt(poiItem.getPoiId(), poiItem.getTitle(), poiItem.getSnippet(), poiItem.getLatLonPoint().getLongitude(), poiItem.getLatLonPoint().getLatitude());
        for (int i = 0; i < historyPoiItemList.size(); i++) {
            if (historyPoiItemList.get(i).getId().equals(poiItem.getPoiId()))
                return;
        }
        historyPoiItemList.add(0, poiItemExt);
//        ParcelableUtils.save(PositionSelectActivity.this,historyPoiItemList);
        SaveBeanUtil.putBean(PositionSelectActivity.this, Const.POSITION_HISTORY, historyPoiItemList);
    }

    private void removeHisPosition(int position) {
        if (poiItemList == null)
            return;
        if (position > poiItemList.size() - 1)
            return;
        poiItemList.remove(position);
        historyPoiItemList.remove(position);

        positionAdapter.notifyDataSetChanged();
        SaveBeanUtil.putBean(PositionSelectActivity.this, Const.POSITION_HISTORY, historyPoiItemList);


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.iv_back, R.id.iv_delete, R.id.ll_position_nearby, R.id.ll_position_history, R.id.ll_myposition,R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_delete:
                break;
            case R.id.ll_position_nearby:
                /*Intent nearbyIntent = new Intent(PositionSelectActivity.this,NearbyPosition.class);
                startActivity(nearbyIntent);*/
                view_near.setVisibility(View.VISIBLE);
                view_history.setVisibility(View.INVISIBLE);
                view_myposition.setVisibility(View.INVISIBLE);
                tvConfirm.setVisibility(View.GONE);
                poiItemList.clear();
                getSearchPosition(LIST_TYPE_NEAR);
                break;
            case R.id.ll_position_history:
                /*Intent hisIntent = new Intent(PositionSelectActivity.this,HistoryPosition.class);
                startActivity(hisIntent);*/
                view_near.setVisibility(View.INVISIBLE);
                view_history.setVisibility(View.VISIBLE);
                view_myposition.setVisibility(View.INVISIBLE);
                tvConfirm.setVisibility(View.GONE);
                getHistoryPosition();
                break;
            case R.id.ll_myposition:
                view_near.setVisibility(View.INVISIBLE);
                view_history.setVisibility(View.INVISIBLE);
                view_myposition.setVisibility(View.VISIBLE);
                tvConfirm.setVisibility(View.VISIBLE);
                poiItemList.clear();
                positionAdapter.notifyDataSetChanged();
                getMyPosition();
                break;
            case R.id.tv_confirm:
                Intent intent = new Intent(PositionSelectActivity.this,PositionAddActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (view_myposition.getVisibility() == View.VISIBLE)
        {
            getMyPosition();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent) {
        if ("finishPotisionSelect".equals(messageEvent.getMessage())) {
            finish();
        }
    }


}
